<template>
  <base-breadcrumb :title="title">
    <div class="about-master-container">
      <a-card :bordered="false">
        <title-name :title="type == 'edit' ? '科技管理计划编辑' : '科技管理计划新增'" />
        <a-spin :spinning="loading[0] || loading[1]">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
          >
            <a-row>
              <a-col span="16">
                <a-form-model-item
                  label="所属单位"
                  prop="projectId"
                >
                  <org-tree-select
                          is-need-auth
                          is-auto-select-first
                          check-strictly
                          :is-query-projec-detail="false"
                    v-model="form.projectId"
                          @select="selectOrg"
                  />
                </a-form-model-item>
              </a-col>
<!--              <a-col span="16">-->
<!--                <a-form-model-item-->
<!--                        label="分公司"-->
<!--                        prop="branchCompanyId"-->
<!--                >-->
<!--                  <SelectSubCompany-->
<!--                          v-model="form.branchCompanyId"-->
<!--                          placeholder="请选择"-->
<!--                          @change="form.projectId == ''"-->
<!--                  />-->
<!--                </a-form-model-item>-->
<!--              </a-col>              -->
<!--              <a-col span="8">-->
<!--                <a-form-model-item-->
<!--                  label="项目名称"-->
<!--                  prop="projectId"-->
<!--                >-->
<!--                  <SelectProject-->
<!--                    v-model="form.projectId"-->
<!--                    :is-clear="type != 'edit'"-->
<!--                    placeholder="请选择"-->
<!--                    :form="form"-->
<!--                  />-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->
              <a-col span="8">
                <a-form-model-item
                  prop="planAchievementsName"
                  label="计划成果名称:"
                >
                  <BaseInput
                    v-model="form.planAchievementsName"
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>

              <a-col span="8">
                <a-form-model-item
                  prop="achievementsTypeId"
                  label="成果分类:"
                >
                  <a-select
                    v-model="form.achievementsTypeId"
                    placeholder="请选择成果分类"
                    @change="changeType"
                  >
                    <a-select-option
                      v-for="item in archivement"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{
                        item.name
                      }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item
                  prop="planAchievementsLevelId"
                  label="计划成果等级:"
                >
                  <a-select
                    v-model="form.planAchievementsLevelId"
                    placeholder="请选择成果等级"
                  >
                    <a-select-option
                      v-for="item in archiveLevel"
                      :key="item.id"
                    >
                      {{ item.levelName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col span="8">
                <a-form-model-item
                  prop="planCompleteEmployeeId"
                  label="计划完成人"
                >
                  <a-tag
                    v-for="item in Personnel"
                    :key="item.userId"
                    closable
                    @close="Personnel = Personnel.filter((v) => v.userId !== item.userId)"
                  >
                    {{ item.name }}
                  </a-tag>
                  <a-button v-if="!(Personnel && Personnel.length !== 0)" @click="visible = true">选择人员</a-button>
                </a-form-model-item>
              </a-col>

              <a-col span="8">
                <a-form-model-item
                  prop="planCompleteDate"
                  label="计划完成日期:"
                >
                  <a-date-picker
                    v-model="form.planCompleteDate"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                  />
                </a-form-model-item>
              </a-col>

              <a-col span="8">
                <a-form-model-item
                  label="年度:"
                >
                  <b-input
                    v-model="form.year"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col span="24">
                <a-form-model-item
                  label="上传附件:"
                  prop="fileArrays"
                >
                  <upload-list
                    business-code="STM03"
                    :upload-arrys.sync="form.fileArrays"
                    multiple
                    @fileArrysData="fileArrysData"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-spin>
        <div class="page-btn-right-top">
          <a-button
            v-if="(type == 'edit' && (planStatusCode == '0' || planStatusCode == '3')) || type == 'add'"
            :loading="loading[0]"
            :disabled="loading[1]"
            type="primary"
            class="btn_right"
            @click="submit(0)"
          >
            {{ planStatusCode == '3' ? '保存' : '保存草稿' }}
          </a-button>
          <a-button
            v-if="(type == 'edit' && (planStatusCode == '0' || planStatusCode == '3')) || type == 'add'"
            :loading="loading[1]"
            :disabled="loading[0]"
            type="primary"
            class="btn_right"
            @click="submit(1)"
          >
            提交
          </a-button>
          <a-button
            v-if="checkVisibleInDetail"
            type="primary"
            @click="handleActiveClose"
          >
            关闭
          </a-button>
        </div>
      </a-card>
    </div>

    <SelectPerson
      mode="single"
      :visible.sync="visible"
      title="添加计划完成人"
      :list.sync="Personnel"
      @getSelectPerson="getSelectPerson"
    />
   <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import { getPlan, getArchivementsList, FromtypeIdGetLevel, addPlan, editPlan, removePlan } from '@/api/science'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import UploadList from '@/components/UploadList'
import BaseEditPage from '@/views/baseEditPage'
import moment from 'moment'
import SelectPerson from '@/components/Select/SelectPerson'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    UploadList,
    SelectSubCompany,
    SelectProject,
    SelectPerson
  },
  data() {
    let validator = (rule, value, callback) => {
      if (value && value.length > 0) {
        callback()
      } else {
        callback('请上传附件！')
      }
    }
    return {
      loading: { 0: false, 1: false },
      data: {},
      typeId: '',
      project: [],
      modalType: 'close',
      modalVisible: false,
      archivement: [],
      Personnel: [],

      visible: false,
      removeApi: { remove: removePlan }, // 删除api
      planStatusCode: '', // 审批状态
      company: [],
      archiveLevel: [],
      form: {
        planAchievementsName: '',
        projectName: '',
        typeId: '',
        orgId: '',
        levelId: '',
        planCompleteDate: '',
        planCompleteEmployee: '',
        planCompleteEmployeeId: '',
        joinEmployees: [],
        fileArrays: [],
        year: moment().format('YYYY')
      },
      rules: {
        branchCompanyId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        planAchievementsName: [{ required: true, message: '请输入计划成果名称', trigger: 'change' }],
        achievementsTypeId: [{ required: true, message: '请选择成果分类', trigger: 'change' }],
        planCompleteEmployeeId: [{ required: true, message: '请添加计划完成人', trigger: 'change' }],
        planCompleteDate: [{ required: true, message: '请选择计划完成日期', trigger: 'change' }],
        planAchievementsLevelId: [{ required: true, message: '请选择计划成果等级', trigger: 'change' }],
        fileArrays: [{ required: true, validator: validator, trigger: 'change' }]
      },
      projectName: '',
      options: [
        {
          value: '四川分公司',
          label: '四川分公司',
          children: [
            {
              value: '四川',
              label: '四川',
              children: [
                {
                  value: '成都',
                  label: '成都'
                }
              ]
            }
          ]
        }
      ],
      list: '',
      id: '',
      dataList: [],
      employeeName: '',
      column: 2,
      title: '',
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    if (this.type === 'edit') {
      this.title = '编辑计划'
      this.getData()
    } else {
      this.title = '新增计划'
    }
    // this.getOrgTree()
    this.getArchivementsList()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('achievements_plan')
  },
  methods: {
    selectOrg(val) {
      if(val.length > 1) {
        this.form.branchCompanyId = val[val.length - 2].orgId
      }
    },
    getSelectPerson(e){
      if (this.Personnel.length > 0) {
        this.form.planCompleteEmployee = this.Personnel[0].name
        this.form.planCompleteEmployeeId = this.Personnel[0].userId
        this.$refs.ruleForm.validateField('planCompleteEmployeeId')
      }
    },
    async fileArrysData(list) {
      this.$refs.ruleForm.validateField('fileArrays')
    },
    submit(e) {
       this.setProcessConfig = null;
      if (this.Personnel.length > 0) {
        this.form.planCompleteEmployee = this.Personnel[0].name
        this.form.planCompleteEmployeeId = this.Personnel[0].userId
      }
      this.$refs.ruleForm.validate((val) => {
        if (val) {
          if (e === 1) {
            this.submitApprovalConfirm(this.processConfig,async (flag) => {
              if(!flag) {
                this.loading[e] = false
                return
              }
              this.loading[e] = true
              let form = this.$clone(this.form)
              form.planStatusCode = this.planStatusCode == 3 && e == 0 ? this.planStatusCode : e
              let url = { edit: editPlan, add: addPlan }[this.type]
              url(form)
                .then((res) => {
                  this.loading[e] = false
                  if (res.code == 200 || res.data.code == 200) {
                    this.$message.success({ edit: '编辑', add: '新增' }[this.type] + '成功')
                  if(e*1===1) {
                  //提交时，返回id
                      this.businessId = res.data.planId || this.id;
                      this.setProcessConfig = this.processConfig;
                      return
                  }else{
                    this.$multiTab.close()
                    }
                  }
                })
                .catch(() => {
                  this.loading[e] = false
                })
            })
          } else {
            this.loading[e] = true
            // e == 0 && this.$refs.ruleForm.clearValidate()
            let form = this.$clone(this.form)
            form.planStatusCode = this.planStatusCode == 3 && e == 0 ? this.planStatusCode : e
            let url = { edit: editPlan, add: addPlan }[this.type]
            url(form)
              .then((res) => {
                this.loading[e] = false
                if (res.code == 200 || res.data.code == 200) {
                  this.$message.success({ edit: '编辑', add: '新增' }[this.type] + '成功')
                  this.$multiTab.close()
                }
              })
              .catch(() => {
                this.loading[e] = false
              })
          }
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    changeType(value) {
      let _this = this
      _this.typeId = value
      this.$set(this.form, 'planAchievementsLevelId', '')
      FromtypeIdGetLevel({ typeId: _this.typeId, status: '1' }).then((res) => {
        if (res.code == 200) {
          _this.archiveLevel = res.data.data
        }
      })
    },
    getArchivementsList() {
      getArchivementsList({ status: '1' }).then((res) => {
        if (res.code == 200) {
          this.archivement = res.data
        }
      })
    },
    getData() {
      this.loading[0] = true
      getPlan({ planId: this.id })
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            this.form = res.data
            if (this.form.planCompleteEmployeeId) {
              this.Personnel = [
                { name: this.form.planCompleteEmployee, userId: this.form.planCompleteEmployeeId }
              ]
            }
            this.planStatusCode = res.data.planStatusCode
            return res
          }
        })
        .then((res) => {
          if (res.code === 200) {
            FromtypeIdGetLevel({ typeId: res.data.achievementsTypeId, status: '1' }).then((res) => {
              if (res.code == 200) {
                this.archiveLevel = res.data.data
              }
            })
          }
        })
        .catch((res) => {
          this.loading[0] = false
        })
    },
    handleCancel() {
      this.$multiTab.close()
    }
  }
}
</script>
